<template>
  <div>
    <h3>注册页面</h3>
    <el-form :model="ruleUser" status-icon :rules="rules" ref="ruleUser" label-width="100px" class="demo-ruleUser" style="width:600px;margin:0 auto">
        <el-form-item label="用户名" prop="username">
            <el-input  v-model="ruleUser.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password1">
            <el-input type="password" v-model="ruleUser.password1" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="password2">
            <el-input type="password" v-model="ruleUser.password2" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="mobile">
            <el-input  v-model="ruleUser.mobile" ></el-input>
        </el-form-item>

        <el-form-item  prop="imageCode">
            <el-input  v-model="ruleUser.imageCode" ></el-input>
            <img class="img" :src="iamgeUrl" alt="图形验证码" @click="image">
        </el-form-item>
       
        <el-form-item>
           
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
        </el-form-item>
</el-form>

  </div>
</template>

<script>
import  {v4 as uuid4} from 'uuid';
import axios from 'axios'
  export default {
    data() {
      var validateUsername=(rule, value, callback) => {
          if (!value === ''){
            return callback(new Error('请输入用户名'))
          }
          const nameRule=/^[a-zA-Z]\w{4,15}$/
          if(nameRule.test(value)){
            //格式不正确
              axios.get('user/username/'+value+'/')
              .then(resp=>{
                console.log(resp);
                if(resp.data.code == 200){
                    return callback()
                }else{
                    return callback(new Error(resp.data.msg))
                }
            })
            .catch(err=>{
                console.log(err);
            })
            
          }else{
            return callback(new Error('用户名的格式不正确'))
          }
      };
      
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.ruleUser.password1 !== '') {
            alert('输入密码成功')
          }
          callback();
        }
      };
      var validatePassword2 = (rule, value, callback) => {
        if (value === '') {
            return callback(new Error('请输入确认密码'));
        }
        
        if(value != this.ruleUser.password1){
            return callback(new Error('两次密码不一致'))
        }else{
            return callback() 
        }
      };
      var validateMobile=(rule, value, callback)=>{
          if(value === ''){
            callback(new Error('请输入手机号'));
          }
          const mobileRule=/^1[3-9]\d{9}$/
          if(mobileRule.test(value)){
              axios.get('user/mobile/'+value+'/')
              .then(resp=>{
                console.log(resp);
                if(resp.data.code == 200){
                    return callback()
                }else{
                    return callback(new Error(resp.data.msg))
                }
            })
            .catch(err=>{
                console.log(err);
            })
      } else{
              return callback(new Error('手机号的格式不正确'))
      }
      
      };
      var validateImageCode =(rule, value, callback)=>{
        if(value === ''){
            callback(new Error('请输入图片验证码'));
        }
        axios.post('user/img/'+imgId+'/',{'code':value})
              .then(resp=>{
                console.log(resp);
                if(resp.data.code == 200){
                    return callback()
                }else{
                    return callback(new Error(resp.data.msg))
                }
            })
            .catch(err=>{
                console.log(err);
            })
      } 
    
      return{
        iamgeUrl:'',
        imgId:"",
        ruleUser: {
          username:'',
          password1:"",
          password2: '',
          checkPass: '',
          mobile:'',
          imageCode: "",
        },

      
     rules: {
           username: [ 
            { validator: validateUsername, trigger: 'blur' }
          ],
          password: [
            { validator: validatePass, trigger: 'blur' }
          ],
            password2: [ 
            { validator: validatePassword2, trigger: 'blur' }
          ],
          mobile:[
            {validator:validateMobile,trigger: 'blur'}
          ],
          imageCode:[
            {validator:validateImageCode,trigger: 'blur'}
          ]


        },
      }
},
    mounted(){
        this.image()
    },
    methods: {
        image() {
            this.imgId = uuid4()
              this.iamgeUrl = "user/img/" + this.imgId + "/"
            },
        submitForm(formName) {
          // 再次校验表单
            this.$refs[formName].validate((valid) => {
              if (valid) { //如果再次校验通过
                alert('submit!');
                // 前后端同意的情况下可以直接写 ruleUser   不统一一个个组装跟老师发的一样
                axios.post('user/reg/',this.ruleUser)
                .then(resp=>{
                  console.log(resp);
                  if(resp.data.code == 200){
                    alert('注册成功')
                    this.$router.push('/login')
                  }else{
                    alert(resp.data.msg)
                  }
                })
                .catch(err=>{
                  console.log(err);
                })
              } else {
                console.log('error submit!!');
                return false;
              }
            });
      },
        // 用户注册
    //  reg() {
    //     axios.post("/user/reg/", {
    //           username: this.ruleUser.username,
    //           password1: this.ruleUser.password1,
    //           password2: this.ruleUser.password2,
    //           mobile: this.ruleUser.mobile,
          
    //         })
    //         .then((resp) => {
          
    //           if (resp.data.code ==401) {
    //             alert('注册成功')
    //           } else {
    //             alert('注册失败')
    //           }
    //         })
    //         .catch((err) => {
    //           return Promise.reject(err);
    //         });
    //     }, 
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    }
    }

</script>

<style>
.img{
  float: right;
  width:30%
}
</style>